package com.simple.card.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.simple.card.repository.tenantbank", sqlSessionTemplateRef  = "tenantbankSqlSessionTemplate")
public class DataSource3Config {
    @Bean(name = "tenantbankData")
    @ConfigurationProperties(prefix = "spring.datasource.tenantbank") // application.properteis中对应属性的前缀
    public DataSource tenantbankData() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "tenantbankSqlSessionFactory")
    public SqlSessionFactory tenantbankSqlSessionFactory(@Qualifier("tenantbankData") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        //bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/repository/sentinel/*.xml"));
        return bean.getObject();
    }

    @Bean(name = "tenantbankTransactionManager")
    public DataSourceTransactionManager tenantbankTransactionManager(@Qualifier("tenantbankData") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "tenantbankSqlSessionTemplate")
    public SqlSessionTemplate tenantbankSqlSessionTemplate(@Qualifier("tenantbankSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
